import time
import subprocess
mixerImportSuc = False
try:
  import pygame.mixer
  mixerImportSuc = True
except Exception as _e:
  print('[warn]import pygame.mixer failed! e=', _e)


allSound = {}


class Sound:
  def __init__(self, soundPath):
    st = time.time()
    self.soundPath = soundPath
    self.pygame_mixer_sound = None
    if mixerImportSuc:
      if soundPath in allSound:
        self.pygame_mixer_sound = allSound[soundPath]
      else:
        self.pygame_mixer_sound = pygame.mixer.Sound(soundPath)
        allSound[soundPath] = self.pygame_mixer_sound
        print('初始化Sound完毕！', soundPath, time.time() - st)

  def play(self):
    if self.pygame_mixer_sound is not None:
      self.pygame_mixer_sound.play()
    else:
      try:
        subprocess.call(['play-audio', self.soundPath], shell=False)
      except Exception as e:
        print(f'[warn] Failed to play audio using subprocess: {e}')
